#!/usr/bin/python3

# -*- coding: UTF-8 -*- 

import sys       
import os
import re        
import subprocess


linx_mac_def_file = "/sys/kernel/security/linx/mac_default_label"
linx_mac_sub_file = "/sys/kernel/security/linx/mac_subject_label"
linx_mac_rules_file = "/sys/kernel/security/linx/mac_rules"
linx_mbc_file     = "/sys/kernel/security/linx/mbc"
linx_net_doi_file = "/sys/kernel/security/linx/netlabel/doi"
linx_net_cat_file = "/sys/kernel/security/linx/netlabel/categories"
linx_net_amb_file = "/sys/kernel/security/linx/netlabel/ambient"

d_user = dict()
d_group = dict()
d_sub_label = dict()
d_rules_label = dict()
d_amb_label = dict()
d_mbc_label = dict()

debug = False


# check the effective user and security directory
def check_user_and_dir():
    try:
        # check if directory /sys/kernel/security/linx is exists
        os.listdir("/sys/kernel/security/linx")
    except(OSError):
        print("Sorry, your system is not the security OS!")
        exit()

    # check user is root or secadmin or not
    euid = os.geteuid()
    if not (euid == 0 or euid == 997):
        print("Sorry, you are not root or secadmin, permissions denied!")
        exit()



# checking field 
def check_field(f, flg=''):
    # convert Octal and Hexadecimal number to Decimal
    if f == '':
        print("Sorry, [%s] is not a valid number!" %f)
        return False
    n = ''
    f=str(f)
    try:
        if f != '-':
            if re.match('^[1-9]\d*$', f) or f.strip() == '0':
                n = int(f)
            elif (len(f.strip()) > 1 and f.strip()[0] == '0' and f.strip()[1] != 'x' and f.strip()[1] != 'X'):
                n = int(f, 8)
            elif (len(f.strip()) > 1 and f.strip()[0] == '0' and (f.strip()[1] == 'x' or f.strip()[1] == 'X')):
                n = int(f, 16)
            else:
                print("You input [%s] is out of range!" %f)
                return False
        if flg == 'doi':
            if (int(n) > 0 and int(n) < 2**32):
                return True
            else:
                print("You input Doi [%s] is out of range!" %(int(f)))
                return False
        elif flg == 'def':
            if (int(n) >= 0 and int(n) < 2**64):
                return True
            else:
                print("You input Default label [%s] is out of range!" %(int(f)))
                return False

        elif not (f == '-' or (int(n) >= 0 and int(n) < 2**64) ):
            print(("You input field '%s' is mistaken!") %f)
            return False
        elif f == '-':
            return '-'
        elif int(n) == 0:
            return '-1'
        else:return int(n)
    except(ValueError or IndexError):
        print("Sorry, [%s] is not a valid number!" %f)
        return False

# write values to /sys/kernel/security/linx/mac_subject_label
def write_mac_sub_file():
    if debug:
        f = sys.stdout
    else:
        f = open(linx_mac_sub_file, 'w')

    subl = ''
    for k in sorted(d_sub_label.keys()):
        s = '%s %s %s %s\n' %(k, d_sub_label[k].field1, d_sub_label[k].field2, d_sub_label[k].field3)
        subl += s
    f.write(subl)
    if not debug: f.close()
    print("Write mac_subject_label Successfully!")
    return True


class Subject:
    def __init__(self, uid, field1, field2, field3):
        self.uid = uid
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3

def check_uid(uid):
    if uid == '-' or re.match("^\d*$", uid):
        return True
    else:return False

def set_mac_sub_label(uid, f1='', f2='', f3=''):
    if (f1 == '' and f2 == '' and f3 == ''):
        if uid in d_sub_label:
            del d_sub_label[uid]
            return True
    if not (check_field(f1) and check_field(f2) and check_field(f3)):
        print("field is error!")
        return False
    elif not check_uid(uid):
        print("uid is errot!")
        return False
    else :
        d_sub_label[uid] = Subject(uid, f1, f2, f3)
    return True

def get_mac_sub_label():
    f = open(linx_mac_sub_file, 'r')
    for l in f.readlines():
        l = l.split('\n')[0]
        uid = l.split(' ')[0]
        d_sub_label[uid] = Subject(uid, l.split(' ')[1], l.split(' ')[2], l.split(' ')[3])
    f.close()


# write values to /sys/kernel/security/linx/mac_default_label
def write_mac_def_file(f1, f2, f3):
    if not (check_field(f1, 'def') and check_field(f2, 'def') and check_field(f3, 'def')):
        print("field is error!") 
        return False

    if debug:
        f = sys.stdout
    else:
        f = open(linx_mac_def_file, 'w')
    default = f1 + ' ' + f2 + ' ' + f3 + '\n'
    f.write(default)
    if not debug: f.close()
    print("Write mac_default_label Successfully!")
    
def get_mac_def_label():
    f = open(linx_mac_def_file, 'r')
    l = f.readline().split()
    if len(l) != 3:
        print("Sorry, mac default label error!")
        return False
    f.close()
    return (l[0], l[1], l[2])

# write values to /sys/kernel/security/linx/mac_rules
def write_mac_rules_file():
    if debug:
        f = sys.stdout
    else:
        f = open(linx_mac_rules_file, 'w')

    macrul = ''
    for k in sorted(d_rules_label):
        s = '%s %s\n' %(k, d_rules_label[k])
        macrul += s
    f.write(macrul)
    if not debug: f.close()
    print("Write mac_rules Successfully!")
    

def set_mac_rules_label(f, rel, perm=''):
    keyword = f + ' ' + rel
    if perm == '':
        del d_rules_label[keyword]
        return True

    if not (f in ['f1','f2','f3']):
        print(("You input field '%s' is mistaken!") %f)
        return False
    if not (rel in  ['>', '<', '}', '{', '=', '!']):
        print(("You input relations '%s' is mistaken!") %rel)
        return False
    if not (perm in ['-w', 'r-', '--', 'rw']):
        print(("You input permissions '%s' is mistaken!") %perm)
        return False

    d_rules_label[keyword] = perm
    return True
    
def get_mac_rules_label():
    f = open(linx_mac_rules_file, 'r')
    for l in f.readlines():
        l = l.split('\n')[0]
        keyword = l.split(' ')[0] + ' ' + l.split(' ')[1]
        d_rules_label[keyword] = l.split(' ')[2]
    f.close()

## write values to /sys/kernel/security/linx/mbc
def write_mbc_file():
    if debug:
        f = sys.stdout
    else:
        f = open(linx_mbc_file, 'w')

    mbcl = ''
    for k in sorted(d_mbc_label):
        # if d_mbc_label[k] is empty, continue
        if not d_mbc_label[k]:
            continue
        obj_l = ''
        # convert the object list to a long string
        for obj_rwx in d_mbc_label[k]:
            obj_l += '\n' + obj_rwx
        s = "%s%s\n\n" %(k, obj_l)
        mbcl += s
    f.write(mbcl)
    if not debug: f.close()
    print("Write mbc Successfully!")


def set_mbc_label(sub, ob, perm=''):
    if sub in d_mbc_label:
        n = 0
        for o in d_mbc_label[sub]:
            o1 = o.rstrip() # remove the end '\n'
            o1 = o[:len(o)-4]   # remove rwx 
            if o1 == ob:
                d_mbc_label[sub].remove(d_mbc_label[sub][n])
                print(("Remove [%s, %s] from mbc policy!") %(sub, ob))
                break
            n += 1
        if perm != '':
            d_mbc_label[sub].append(ob + ' ' + perm )
    else:
        d_mbc_label[sub] = []
        d_mbc_label[sub].append(ob + ' ' + perm )
    return True


# if fl != '', it means get_mbc_label from CLI (stdin)
def get_mbc_label(fl=''):
    if fl == '':
        f = open(linx_mbc_file, 'r')
        resolve(f.readlines(), 'f')
        f.close()
    else: 
        resolve(fl)
    return True

def resolve(lines, flg=''):
    # if flg is not '', it means information is
    # not from linx_mbc_file
    objlist = []
    obj_rwx = ''
    sub = obj = rwx = ""
    for l in lines:
        # if match a blank line, todo
        if re.match('^s*$', l):
            sub = objlist[0]
            objlist.remove(sub)
            # if get info from linx-mbc-file and the first Character is not '"',
            # then add '"' to the head and the end to the string
            if flg != '' and sub[0] != '"':
                sub = '"' + sub + '"'

            s = get_real_file(sub)
            if not s:
                return False
            
            n_list = []
            for i in objlist:
                i = i.rstrip()
                rwx = i[len(i)-3:]

                # now i is object
                obj = i[0:len(i)-4]
                # if get info from linx-mbc-file and the first Character is not '"',
                # then add '"' to the head and the end to the string
                if flg != '' and obj[0] != '"':
                    obj = '"' + obj + '"'

                o = get_real_file(obj)
                if not o:
                    return False
                n_list.append(o + ' ' + rwx)

            d_mbc_label[s] = n_list
            objlist = []
        else:
            # remove the blanks from the head and the end
            l = l.strip()
            # if the end is '\', it is not a complete Sentence
            if l[-1] == '\\':
                obj_rwx = obj_rwx + l
            else:
                obj_rwx = l
                objlist.append(obj_rwx)
                obj_rwx = ''
    return True

''' process file name in quote space '''
def process_quote_name(fl, quote):
    fname = ''
    n = 0
    while(n<len(fl)):
        if fl[n] == quote:
            return [fname, n]
        if fl[n] == '\n':
            return False
        if fl[n] == '\\' and (fl[n+1] == '\\' or fl[n+1] == '"' or\
                    fl[n+1] == "'" or fl[n+1] == '\n'):
            n += 1
        fname += fl[n]
        n += 1
    return False

def check_file_name(fl):
    fname = ''
    n = 0
    while(n<len(fl)):
        if fl[n] == '\\':
            n += 1
            fname += fl[n]
            n += 1
            continue
        if fl[n] == ' ' or fl[n] == '\n':
            print("Match '\\n' without quotes space, filename is [%s]!" %fname)
            return fname
        quote = fl[n]
        if quote == '"' or quote == "'":
            n += 1
            l = []
            l = process_quote_name(fl[n:], quote)
            if not l:
                return False
            fn,lenth = l
            n += lenth
            fname += fn
            n += 1
            continue
        fname += fl[n]
        n +=1
    return fname


def get_real_file(f):
    # if f is none, return error
    if f == '':
        print(("Error: you input '%s' is not a valid file!") %f)
        return False
    fl = check_file_name(f)
    if not fl:
        print(("Error: check filename '%s' error!") %fl)
        return False

    if not os.path.exists(fl):
        print(("Error: '%s' is not exists!") %fl)
        return False
    else:
        return quote_name_add(os.path.realpath(fl)) 

# set and user label 
class User:
    def __init__(self, id, login_name, group_name, field1, field2, field3):
        self.id   = id
        self.login_name = login_name
        self.group_name = group_name
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3

''' Get initial data from /etc/group, /etc/passwd, 
 and /sys/kernel/security/linx/mac_subject_label
 '''
def init_user():
    f_group = open('/etc/group')
    for l in f_group:
        fl = l.split(':')
        d_group[fl[2]] = fl[0]
    f_group.close()

    f_passwd = open('/etc/passwd')
    for l in f_passwd:
        fl = l.split(':')
        f_1=f_2=f_3 = "-"
        ''' uid username usergroup field1 field2 field3 '''
        if fl[2] in d_sub_label:
            f_1 = d_sub_label[fl[2]].field1
            f_2 = d_sub_label[fl[2]].field2
            f_3 = d_sub_label[fl[2]].field3
         
        d_user[fl[2]] = User(fl[2], fl[0], d_group.get(fl[3]) or fl[3], f_1, f_2, f_3)
    if '-' in d_sub_label:
        d_user['-'] = User('-', '-', '-', d_sub_label['-'].field1, \
                d_sub_label['-'].field2, d_sub_label['-'].field3)
    else:
        d_user['-'] = User('-', '-', '-', '', '', '')

    f_passwd.close()


# process 
class Process:
    def __init__(self, id, user_name, cmd):
        self.id        = id
        self.user_name = user_name
        self.cmd       = cmd


''' process mac label '''
def get_process():
    p = subprocess.Popen("ps -Ao pid= -o euser= -o cmd=", stdin=None, stdout=subprocess.PIPE, shell=True)
    l = list()
    for s in p.stdout:
        fl=s.decode().split()
        l.append(Process(fl[0], fl[1], ' '.join(fl[2:])))
    p.wait()
    return l

def get_process_mac(pid):
    cmd_s = 'cat /proc/%s/linx/mac_label' %(pid)
    f1 = f2 = f3 = '-'
    if debug:
        print(cmd_s)
    else :
        p = subprocess.Popen(cmd_s, stdin=None, stdout=subprocess.PIPE, shell=True)
        for l in p.stdout:
            t = l.decode()
            f1,f2,f3 = t.split() or ['-','-','-']
        p.wait()
    return (f1, f2, f3)

''' process mbc label '''
def get_process_mbc(pid):
    cmd_s = 'cat /proc/%s/linx/mbc' %(pid)
    mbc_label = ""
    if debug:
        print(cmd_s)
    else :
        p = subprocess.Popen(cmd_s, stdin=None, stdout=subprocess.PIPE, shell=True)
        for l in p.stdout:
            t = l.decode()
            if t :
                # remove The first row, remove space sentence
                if re.match('Name', t) or re.match('^s*$', t): 
                    continue
                else :
                    mbc_label += t 
        p.wait()
    return mbc_label


#
# files 
#
class File:
    def __init__(self, name, mode, user, group, field1, field2, field3, bypass, bypass_def):
        self.name = name
        self.mode = mode
        self.user = user
        self.group = group
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3
        self.bypass = bypass
        self.bypass_def = bypass_def

def construct_file_name(l):
     # 0th item is '/', 1st item, if have, may be 'usr'...
    w_n = '/%s' %('/'.join(l[1:]))
    f_n = l[-1]
    return (w_n, f_n)


# get file security labels
def get_file_label(f_name):
    cmd_s = 'getfmac %s' %(f_name)
    f1 = f2 = f3 = flg1 = flg2 = "-"
    if debug:
        print(cmd_s)
    else:
        p = subprocess.Popen(cmd_s, stdin=None, stdout=subprocess.PIPE, shell=True)
        for l in p.stdout:
            t = l.decode()
            if re.match("flag:", t):
                if re.search("bypass-mac-default", t):
                    flg2 = True
                if (re.search("bypass-mac\n", t) or re.search("bypass-mac,", t)):
                    flg1 = True
            elif re.match("f1", t):
                tmp = t.split(' ')[1]
                tmp = tmp.split('(')[1]
                f1 = tmp.split(')')[0]
            elif re.match("f2", t):
                tmp = t.split(' ')[1]
                tmp = tmp.split('(')[1]
                f2 = tmp.split(')')[0]
            elif re.match("f3", t):
                tmp = t.split(' ')[1]
                tmp = tmp.split('(')[1]
                f3 = tmp.split(')')[0]

    p.wait()
    return (f1, f2, f3, flg1, flg2)

''' get file local stat'''
def stat_file(fnl):
    w_n, f_n = construct_file_name(fnl)

    w = quote_name_add(w_n)
    cmd = "stat --format='%%A,%%U,%%G' %s" %w
    m = u = g = ''
    p1 = subprocess.Popen( cmd, stdin=None, stdout=subprocess.PIPE, shell=True)
    for l1 in p1.stdout:
        m, u, g = l1.decode().split(',')

    p1.wait()
    f1, f2, f3, flg1, flg2 = get_file_label(w)
    return File(f_n, m, u, g, f1, f2, f3, flg1, flg2)

''' get file tree'''
def get_file(fnl, list_dir=False):
    if not list_dir: 
        return [stat_file(fnl)]

    w_n, f_n = construct_file_name(fnl)

    p = subprocess.Popen("ls -A '%s'" %(w_n), stdin=None, stdout=subprocess.PIPE, shell=True)
    l = list()
    for s in p.stdout:
        # erase '\n'
        sub_fn = s.decode()[:-1]
        l.append(stat_file(fnl+[sub_fn]))

    p.wait()
    return l

''' set security label of Specified file or directory '''
def quote_name_add(fl):
    # replace '\' to '\\', so '\n, \t' will be '\\n,\\t'
    fl = re.sub(r'\\',r'\\\\',fl)
    fl = re.sub(r'"',r'\"',fl)
    fl = re.sub(r"'",r"\'",fl)
    fl = re.sub(r' ',r'\ ',fl)
    return fl


def set_file_label(fl, f1="-", f2="-", f3="-", flg1='-', flg2='-'):
    wn, f_n = construct_file_name(fl)
    # w_n is path
    # f_n only is filename

    w_n = quote_name_add(wn)
    fg1, fg2, fg3, flgg1, flgg2 = get_file_label(w_n)

    if not (check_field(f1) and check_field(f2) and check_field(f3)):
        print("You input field is error!")
        return False

    d1 = {}
    d2 = {}
    d1['f1'] = f1
    d1['f2'] = f2
    d1['f3'] = f3

    d2['fg1'] = fg1
    d2['fg2'] = fg2
    d2['fg3'] = fg3

    ''' Call command setfmac ''' 
    for n in 1,2,3:
        fn = 'f'+'%s' %n
        fgn = 'fg'+'%s' %n

        if d1[fn] != d2[fgn]:
            if d1[fn] == "-":
                cmd_s = "setfmac -x %s %s" %(fn, w_n)
            else:
                cmd_s = "setfmac -n %s -v %s %s" %(fn, d1[fn], w_n)
        else:cmd_s = ''
        
        if cmd_s:
            if debug:
                print(cmd_s)
            else:
                p = subprocess.Popen(cmd_s, stdin=None, stdout=sys.stdout, stderr=sys.stderr, shell=True)
                p.wait()


    if flg1 == '-' and flgg1:
        cmd_s = 'setfmac -u bypass-mac %s' %w_n
    elif flg1 and flgg1 == '-':
        cmd_s = 'setfmac -f bypass-mac %s' %w_n
    else:cmd_s = ''
    if cmd_s:
        if debug:
            print(cmd_s)
        else:
            p = subprocess.Popen(cmd_s, stdin=None, stdout=sys.stdout, stderr=sys.stderr, shell=True)
            p.wait()

    if flg2 == '-' and flgg2:
        cmd_s = 'setfmac -u bypass-mac-default %s' %w_n
    elif flg2 and flgg2 == '-':
        cmd_s = 'setfmac -f bypass-mac-default %s' %w_n
    else:cmd_s = ''
    if cmd_s:
        if debug:
            print(cmd_s)
        else:
            p = subprocess.Popen(cmd_s, stdin=None, stdout=sys.stdout, stderr=sys.stderr, shell=True)
            p.wait()
    return True


def set_recursion_label(fl, f1="-", f2="-", f3="-", flg1='-', flg2='-'):
    set_file_label(fl, f1, f2, f3, flg1, flg2)
    w_n, f_n = construct_file_name(fl)
    p = subprocess.Popen("ls -A '%s'" %(w_n), stdin=None, stdout=subprocess.PIPE, shell=True)
    for s in p.stdout:
        # erase '\n'
        sub_fn = s.decode()[:-1]
        set_file_label(fl+[sub_fn], f1, f2, f3, flg1, flg2)
    p.wait()

    p2 = subprocess.Popen("cd '%s'; ls -d */ .*/ 2>/dev/null| egrep -v '(\./|\.\./)' " %(w_n), stdin=None, stdout=subprocess.PIPE, shell=True)
    for s in p2.stdout:
        # erase '\n' and '/'
        sub_fn = s.decode().rstrip('\n/')
        set_recursion_label(fl+[sub_fn], f1, f2, f3, flg1, flg2)

    p2.wait()
    return True


# mac netlabel 
def write_mac_net_doi(d):
    if not check_field(d, 'doi'):
        return False

    if debug:
        f = sys.stdout
    else:
        f = open(linx_net_doi_file, 'w')

    doi = d + '\n'
    f.write(doi)
    if not debug: f.close()
    print("Write netlabel doi Successfully!")


def get_mac_net_doi():
    f = open(linx_net_doi_file, 'r')
    doi = f.readline().split()[0]
    f.close()
    return doi


def check_net_cat(f, s, t):
    if (f not in ['f1','f2','f3','-'] or s not in ['f1','f2','f3','-'] or \
        t not in ['f1','f2','f3','-']) or \
        ((s == f) or (t == f ) or ((s == t) and (s != '-')) or ((s == '-') and (t != '-'))):
        print("You input categories '%s,%s,%s' is error!" %(f,s,t))
        return False
    else: return True

def write_mac_net_cat(f, s="", t=""):
    if not check_net_cat(f, s, t):
       return False

    if s == '-':
        s = ''
    if t == '-':
        t = ''

    if debug:
        fl = sys.stdout
    else :
        fl = open(linx_net_cat_file, "w")

    cat = f + ' ' + s + ' ' + t + '\n'
    fl.write(cat)
    if not debug: fl.close()
    print("Write netlabel categories Successfully!")
    return True
    
def get_mac_net_cat():
    l_cat = ['-', '-', '-']
    f = open(linx_net_cat_file, 'r')
    cat = f.readline().split()
    l_cat[0] = cat[0] 
    if len(cat) > 1:
        l_cat[1] = cat[1] 
    if len(cat) > 2:
        l_cat[2] = cat[2]
    f.close()
    return (l_cat[0], l_cat[1], l_cat[2])


def check_address(n):
    # check the legality of the IP address 
    # address form: 192.168.1.100 or 192.168.1.100/30
    if not re.search('/', n):
        n = n.strip()+'/32'
    try:
        if (re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}$",n) and \
                len([i for i in n.split('/')[0].split('.') if (0<= int(i) <=255)])==4 and\
                (0<= int(n.split('/')[1]) <=32) ):
            return n
        else:
            print("Sorry, [%s] is not a valid IP address!" %n)
            return False
    except(ValueError):
        print("Sorry, [%s] is not a valid IP address!" %n)
        return False

class Netamb:
    def __init__(self, ip, net_field1, net_field2, net_field3):
        self.ip = ip
        self.net_field1 = net_field1
        self.net_field2 = net_field2
        self.net_field3 = net_field3

def set_mac_net_amb(ip, f1='', f2='', f3=''):
    if not re.search('/', ip):
        ip = ip.strip()+'/32'

    if (f1 == '' and f2 == '' and f3 == ''):
        if ip in d_amb_label:
            del d_amb_label[ip]
            return True
    elif check_address(ip):
        if not (check_field(f1) and check_field(f2) and check_field(f3)):
            print("field is error!") 
            return False
        else:
            d_amb_label[ip] = Netamb(ip, f1, f2, f3)
            return True
    else:return False 

def write_mac_net_amb():
    if debug:
        f = sys.stdout
    else :
        f = open(linx_net_amb_file, "w")

    ambient = ''
    for i in sorted(d_amb_label):
        oamb = i + ' ' + d_amb_label[i].net_field1 + ' ' +\
                d_amb_label[i].net_field2 + ' ' + d_amb_label[i].net_field3 + '\n'
        ambient += oamb
    f.write(ambient)
    if not debug: f.close()
    print("Write netlabel ambient Successfully!")
    return True
    
def get_mac_net_amb():
    f = open(linx_net_amb_file, 'r')
    for l in f.readlines():
        l.split('\n')[0]
        ip = l.split()[0]
        d_amb_label[ip] = Netamb(ip, l.split()[1], l.split()[2], l.split()[3])
    f.close()
    return True


def set_biba_config():
    d_sub_label.clear()
    write_mac_sub_file()

    write_mac_def_file('0','0', '0')

    d_rules_label.clear()
    set_mac_rules_label('f1', '>', '-w')
    set_mac_rules_label('f1', '<', 'r-')
    set_mac_rules_label('f1', '=', 'rw')
    write_mac_rules_file()

    d_mbc_label.clear()
    write_mbc_file()

    write_mac_net_doi('12')

    write_mac_net_cat('f1', '-', '-')

    d_amb_label.clear()
    set_mac_net_amb('0.0.0.0/0', '-', '-', '-')
    write_mac_net_amb()

def set_blp_config():
    d_sub_label.clear()
    write_mac_sub_file()

    write_mac_def_file('0','0', '0')

    d_rules_label.clear()
    set_mac_rules_label('f1', '}', 'r-')
    set_mac_rules_label('f1', '{', '-w')
    set_mac_rules_label('f1', '=', 'rw')
    set_mac_rules_label('f1', '!', '--')
    set_mac_rules_label('f2', '>', 'r-')
    set_mac_rules_label('f2', '<', '-w')
    set_mac_rules_label('f2', '=', 'rw')
    write_mac_rules_file()

    d_mbc_label.clear()
    write_mbc_file()

    write_mac_net_doi('12')

    write_mac_net_cat('f1', 'f2', '-')

    d_amb_label.clear()
    set_mac_net_amb('0.0.0.0/0', '-', '-', '-')
    write_mac_net_amb()

def set_typical_config():
    d_sub_label.clear()
    set_mac_sub_label("-", '-', '-', '-')
    set_mac_sub_label("1000", "9223372036854775808", "1", "-")
    write_mac_sub_file()

    write_mac_def_file("9223372036854775808", '0', '0')

    d_rules_label.clear()
    set_mac_rules_label('f1', '}', 'r-')
    set_mac_rules_label('f1', '{', '-w')
    set_mac_rules_label('f1', '=', 'rw')
    set_mac_rules_label('f1', '!', '--')
    set_mac_rules_label('f2', '>', 'r-')
    set_mac_rules_label('f2', '<', '-w')
    set_mac_rules_label('f2', '=', 'rw')
    write_mac_rules_file()

    d_mbc_label.clear()
    write_mbc_file()

    write_mac_net_doi('12')

    write_mac_net_cat('f1', 'f2', '-')

    d_amb_label.clear()
    set_mac_net_amb('0.0.0.0/0', '-', '-', '-')
    write_mac_net_amb()

def set_default_config():
    d_sub_label.clear()
    write_mac_sub_file()

    write_mac_def_file('0','0', '0')

    d_rules_label.clear()
    write_mac_rules_file()

    d_mbc_label.clear()
    write_mbc_file()

    write_mac_net_doi('12')

    write_mac_net_cat('f1', 'f2', 'f3')

    d_amb_label.clear()
    set_mac_net_amb('0.0.0.0/0', '-', '-', '-')
    write_mac_net_amb()

check_user_and_dir()
